<!--
/**
* Copyright (C) 2022-2023 Timber Chain Cloud (TimberCLD). All Rights Reserved.
* 
* @author: luoweijian
* @email: 807301075@qq..com
* @site: https://www.timbercld.com/
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
*  limitations under the License.
*/
-->
<template>
  <el-dialog v-model="options.visible" :title="!formData.id ? t('add') : t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form v-loading="options.loading" :model="formData" :rules="formRules" ref="formRef" @keyup.enter="submitDataFormHandle()" label-width="120px">
      <el-form-item prop="subSystemId" :label="t('subsys.subSystemId')">
        <el-input v-model="formData.subSystemId" :placeholder="t('subsys.subSystemId')" :disabled="!!formData.id"></el-input>
      </el-form-item>
      <el-form-item prop="subSystemName" :label="t('subsys.subSystemName')">
        <el-input v-model="formData.subSystemName" :placeholder="t('subsys.subSystemName')" :disabled="!!formData.id"></el-input>
      </el-form-item>
      <el-form-item prop="username" :label="t('subsys.username')">
        <el-input v-model="formData.username" :placeholder="t('subsys.username')"></el-input>
      </el-form-item>
      <el-form-item prop="password" :label="t('subsys.password')" :class="{ 'is-required': !formData.id }">
        <el-input v-model="formData.password" show-password type="password" :placeholder="t('subsys.password')"></el-input>
      </el-form-item>
      <el-form-item prop="realName" :label="t('subsys.realName')">
        <el-input v-model="formData.realName" :placeholder="t('subsys.realName')"></el-input>
      </el-form-item>
      <el-form-item prop="email" :label="t('subsys.email')">
        <el-input v-model="formData.email" :placeholder="t('subsys.email')"></el-input>
      </el-form-item>
      <el-form-item prop="mobile" :label="t('subsys.mobile')">
        <el-input v-model="formData.mobile" :placeholder="t('subsys.mobile')"></el-input>
      </el-form-item>
      <el-form-item prop="comment" :label="t('subsys.comment')">
        <el-input v-model="formData.comment" :placeholder="t('subsys.comment')"></el-input>
      </el-form-item>
      <el-form-item prop="roleIdList" :label="t('subsys.roleIdList')" class="role-list">
        <el-select v-model="formData.roleIdList" multiple :placeholder="t('subsys.roleIdList')">
          <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="status" :label="t('subsys.status')" size="small">
        <el-radio-group v-model="formData.status">
          <el-radio :label="0">{{ t('subsys.status0') }}</el-radio>
          <el-radio :label="1">{{ t('subsys.status1') }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="options.visible = false">{{ t('cancel') }}</el-button>
      <el-button type="primary" @click="submitDataFormHandle()">{{ t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { ResType } from '@/utils/request';
import { ref, reactive, nextTick, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import debounce from 'lodash/debounce';
import type { ElForm } from 'element-plus';
import { ElMessage, FormRules } from 'element-plus';
import { isEmail, isMobile, isNumber } from '@/utils/validate';
import { subApi } from '@/api/global';

// #region 类型
interface FormData {
  id: string;
  subSystemId: string;
  subSystemName: string;
  username: string;
  password: string;
  realName: string;
  email: string;
  mobile: string;
  comment: string;
  roleIdList: any[];
  status: number;
}

type RoleValue = {
  id: string;
  name: string;
};
// #endregion

// #region 属性
const emit = defineEmits<{
  refreshPageHandle: [];
}>();

const { t } = useI18n();
const dialogId = ref('0');

const formRef = ref<InstanceType<typeof ElForm> | null>(null);

// 表单数据
const formData = reactive<FormData>({
  id: '',
  subSystemId: '',
  subSystemName: '',
  username: '',
  password: '',
  realName: '',
  email: '',
  mobile: '',
  comment: '',
  roleIdList: [],
  status: 1,
});
// 页面配置
const options = reactive({
  visible: false,
  loading: false,
  deptListVisible: false,
});
const roleList = ref<RoleValue[]>([]);
const roleIdListDefault = ref<any[]>([]);

// #region 自定义规则
const validateNumber = (rule: any, value: any, callback: any) => {
  if (!isNumber(value)) {
    return callback(new Error(t('subsys.validate.number')));
  }
  callback();
};
const validatePassword = (rule: any, value: any, callback: any) => {
  if (!formData.id && !/\S/.test(value)) {
    return callback(new Error(t('validate.required')));
  }
  callback();
};
const validateEmail = (rule: any, value: any, callback: any) => {
  if (!isEmail(value)) {
    return callback(new Error(t('validate.format', { attr: t('subsys.email') })));
  }
  callback();
};
const validateMobile = (rule: any, value: any, callback: any) => {
  if (!isMobile(value)) {
    return callback(new Error(t('validate.format', { attr: t('subsys.mobile') })));
  }
  callback();
};

// #endregion

// 验证规则
const formRules = reactive<FormRules<FormData>>({
  username: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
  subSystemId: [
    { required: true, message: t('validate.required'), trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' },
  ],
  subSystemName: [{ required: true, message: t('validate.required'), trigger: 'change' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  realName: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
  email: [
    { required: true, message: t('validate.required'), trigger: 'blur' },
    { validator: validateEmail, trigger: 'blur' },
  ],
  mobile: [
    { required: true, message: t('validate.required'), trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' },
  ],
});

// #endregion

// #region 方法
watch([() => dialogId.value], (val1) => {
  formData.id = val1[0];
});

// 获取角色列表
const getSubList = () => {
  subApi.getSubList().then((res) => {
    if (res?.code === 0) {
      Object.assign(roleList.value, res.data);
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 获取信息
const getSubInfo = () => {
  subApi.getSubInfo(formData.id).then(async (res) => {
    if (res?.code === 0) {
      await nextTick();
      Object.assign(formData, res.data);
      // 角色配置, 区分是否为默认角色
      // for (let i = 0; i < res.data.roleIdList.length; i++) {
      //   if (roleList.value.filter((item) => item.id === res.data.roleIdList[i])[0]) {
      //     formData.roleIdList.push(res.data.roleIdList[i]);
      //     continue;
      //   }
      //   roleIdListDefault.value.push(res.data.roleIdList[i]);
      // }
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const init = async () => {
  options.visible = true;
  options.loading = true;
  await nextTick();
  formRef.value?.resetFields();
  roleIdListDefault.value = [];
  await Promise.all([getSubList()]).then(() => {
    if (formData.id) {
      getSubInfo();
    }
  });
  setTimeout(() => {
    options.loading = false;
  }, 500);
};

// 新增子用户
function insertSub() {
  return new Promise<ResType<unknown>>((resolve, reject) => {
    subApi
      .insertSub(formData)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => [reject(err)]);
  });
}
// 更新子用户
function updateSub() {
  return new Promise<ResType<unknown>>((resolve, reject) => {
    subApi
      .updateSub(formData)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => [reject(err)]);
  });
}
// 表单提交
function submit() {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      options.loading = true;
      Object.assign(formData.roleIdList, roleIdListDefault.value);
      let res;
      if (formData.id) {
        res = await updateSub();
      } else {
        res = await insertSub();
      }
      if (res?.code !== 0) {
        ElMessage.error(res.msg);
      } else {
        ElMessage.success(t('prompt.success'));
        options.visible = false;
        emit('refreshPageHandle');
      }
    }
  });
}
// 防抖
const submitDataFormHandle = debounce(submit, 1000, { leading: true, trailing: false });

defineExpose({
  init,
  dialogId,
});
// #endregion
</script>

<style lang="scss">
.subsys__subsys {
  .role-list {
    .el-select {
      width: 100%;
    }
  }
}
</style>
